package com.msk.web.controller.wlhy;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.msk.common.core.controller.BaseController;
import com.msk.common.core.domain.R;
import com.msk.common.core.domain.model.LoginUser;
import com.msk.common.utils.StringUtils;
import com.msk.framework.web.utils.TokenUtils;
import com.msk.sys.domain.Dict;
import com.msk.sys.domain.Office;
import com.msk.sys.domain.User;
import com.msk.sys.service.OfficeService;
import com.msk.sys.service.SystemService;
import com.msk.sys.utils.DictMskUtils;
import com.msk.sys.utils.SiteParamUtil;
import com.msk.wlhy.domain.*;
import com.msk.wlhy.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author llh
 * @date 2023/5/25
 * @description 角色认证信息接口
 */
@Api("角色认证信息接口")
@RestController
@RequestMapping("/api/roleAuthentication")
public class RoleAuthenticationController extends BaseController {

    @Autowired
    private HtDriverFileService htDriverFileService;

    @Autowired
    private HtCarFilesService htCarFilesService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private InformationService informationService;

    @Autowired
    private AreaService areaService;

    @Autowired
    private HtSupplierService htSupplierService;

    /**
     * @author llh
     * @date 2023/6/5
     * @return com.msk.common.core.domain.R<?>
     * @description 校验车牌号是否存在      
     */
    @ApiOperation("校验车牌号是否存在")
    @PostMapping("/checkCarNumber")
    public R<?> checkCarNo(@RequestBody Map<String, String> map) {
        //true:校验通过 false:车牌已存在
        boolean flag = false;
        String carNumber = map.get("carNumber");
        String carId = map.get("carId");
        HtCarFiles htCarFiles = htCarFilesService.findEntityByCarNumber(carNumber);
        if (StringUtils.isBlank(carId) && htCarFiles == null) {
            flag = true;
        } else if (StringUtils.isNotBlank(carId)) {
            if (htCarFiles != null && carId.equals(htCarFiles.getId())) {
                flag = true;
            }
        }
        return R.appOk(flag);
    }

    /**
     * @author llh
     * @date 2023/6/5
     * @return com.msk.common.core.domain.R<?>
     * @description 获取车籍地列表      
     */
    @ApiOperation("获取车籍地列表")
    @PostMapping("/getAreaList")
    public R<?> getAreaList(@RequestBody(required = false) String extId) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Area> list = areaService.findAll();
        for (int i = 0; i < list.size(); i++) {
            Area e = list.get(i);
            if (StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1)) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("name", e.getName());
                map.put("pId", e.getParentId());
                map.put("areaNames", e.getAreaNames());
                mapList.add(map);
            }
        }
        return R.appOk(mapList);
    }

    /**
     * @author llh
     * @date 2023/5/25
     * @return com.msk.common.core.domain.R<?>
     * @description 司机认证接口      
     */
    @ApiOperation("司机认证接口")
    @PostMapping("/saveDriverCar")
    public R<?> saveDriverCar(@RequestBody HtDriverFile htDriverFile) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        int res = 0;
        try {
            boolean flag = false;
            String carId = htDriverFile.getCarId();
            HtCarFiles htCarFiles2 = htCarFilesService.findEntityByCarNumber(htDriverFile.getCarNumber());
            if (StringUtils.isBlank(carId) && htCarFiles2 != null && "3".equals(htCarFiles2.getIsPassCheck())) {
                //已认证
                res = 2;
                return R.appOk(res);
            } else if (StringUtils.isNotBlank(carId)) {
                if (htCarFiles2 != null && !carId.equals(htCarFiles2.getId()) && "3".equals(htCarFiles2.getIsPassCheck())) {
                    res = 2;
                    return R.appOk(res);
                }
            }
            String id = loginUser.getLoginId();
            htDriverFile.setUserId(id);
            User user = systemService.getUser(htDriverFile.getUserId());
            htDriverFile.setUser(user);
            htDriverFile.setIsPassCheck("0");
            htDriverFile.setDriverStatus("0");
            htDriverFile.setPhone(user.getMobile());
            htDriverFile.setFactSupplierName(htDriverFile.getName());
            htDriverFile.setCarLicensePic(htDriverFile.getDrivingLicensePic());
            htDriverFile.setVehicleEnergyType(htDriverFile.getVehicleEnergyType());

            Office parent = new Office();
            parent.setId("0");
            Office office = new Office();
            office.setParent(parent);
            office.setType("");
            List<Office> officeList = officeService.findListOnly(office);
            boolean f1 = officeList != null && officeList.size() != 0,
                    f2 = office != null && office.getId() != null;
            if (f1) {
                office = officeList.get(0);
                if (f2) {
                    htDriverFile.setOffice(office);
                    htDriverFile.setCompany(office);
                } else {
                    Office office1 = new Office();
                    office1.setId("1");
                    htDriverFile.setOffice(office1);
                    htDriverFile.setCompany(office1);
                }
            }
            Integer version = htDriverFile.getVersion();
            if (version == null) {
                htDriverFile.setVersion(0);
            }
            if ("请选择".equalsIgnoreCase(htDriverFile.getBaseOpenAccountName())) {
                htDriverFile.setBaseOpenAccountName("");
            }
            htDriverFileService.saveNewDriver(htDriverFile);

            //司机审核开关如果关闭，补充自动审核通过流程
            if (!SiteParamUtil.isDriver()) {
                HtDriverFile htDriverFileUpdate = htDriverFileService.get(htDriverFile.getId());
                htDriverFileUpdate.setIsPassCheck("1");
                htDriverFileUpdate.setAuditTime(new Date());
                // 设置通用属性
                htDriverFileUpdate.preInsert();
                htDriverFileService.updateStatusNew(htDriverFileUpdate);

                htDriverFile = htDriverFileService.get(htDriverFile.getId());
                //消息提醒
                Information information = new Information();
                information.setUser(htDriverFile.getUser());
                if ("1".equals(htDriverFileUpdate.getIsPassCheck())) {
                    //消息标题
                    information.setTitle("认证审核通过");
                    information.setDetails("您的司机认证申请已经通过，请重新登录");
                } else {
                    information.setTitle("认证审核【没有】通过");
                    information.setDetails("您的司机认证申请【没有】通过");
                }
                //查看状态
                information.setState("0");
                information.setAuditUser(user);
                information.setAuditDate(new Date());
                informationService.save(information);
            }
            //认证中
            res = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.appOk(res);
    }

    /**
     * @author llh
     * @date 2023/5/26
     * @return com.msk.common.core.domain.R<?>
     * @description 司机认证详情接口      
     */
    @ApiOperation("司机认证详情接口")
    @PostMapping("/driverAuthDetails")
    public R<?> driverAuthDetails() {
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        String userId = loginUser.getLoginId();
        String userIdentity = loginUser.getLoginObject();
        Map<String, Object> result = new HashMap<>();
        //司机身份
        if ("1".equals(userIdentity)) {
            HtDriverFile htDriverFile = htDriverFileService.getDriverByUserId(userId);
            if (htDriverFile != null) {
                //状态：0未审核 1已通过 2已驳回
                result = htDriverFileService.getDriverDetails(userId);
                String carType = String.valueOf(result.get("carType"));
                String color = String.valueOf(result.get("carColor"));
                String vehicleEnergyType = String.valueOf(result.get("vehicleEnergyType"));
                String vehicleAreaCode = String.valueOf(result.get("vehicleAreaCode"));

                List<Dict> carTypeDictList = DictMskUtils.getDictListNew("car_type");
                List<Dict> licensePlateColorDictList = DictMskUtils.getDictListNew("license_plate_color");
                List<Dict> vehicleEnergyTypeDictList = DictMskUtils.getDictListNew("vehicle_energy_type");
                Area area = null;
                if (vehicleAreaCode != null) {
                    area = areaService.getById(vehicleAreaCode);
                }
                if (carType != null && StringUtils.isNotEmpty(carTypeDictList)) {
                    carType = DictMskUtils.getDictLabelNew(carType, carTypeDictList, "");
                    result.put("carTypeAlias", carType);
                }
                if (color != null && StringUtils.isNotEmpty(licensePlateColorDictList)) {
                    color = DictMskUtils.getDictLabelNew(color, licensePlateColorDictList, "");
                    result.put("colorAlias", color);
                }
                if (vehicleEnergyType != null && StringUtils.isNotEmpty(vehicleEnergyTypeDictList)) {
                    vehicleEnergyType = DictMskUtils.getDictLabelNew(vehicleEnergyType, vehicleEnergyTypeDictList, "");
                    result.put("vehicleEnergyTypeAlias", vehicleEnergyType);
                }
                if (area != null) {
                    result.put("vehicleAreaName", area.getAreaNames());
                }
            }
        }
        return R.appOk(result);
    }

    /**
     * @author llh
     * @date 2023/6/5
     * @return com.msk.common.core.domain.R<?>
     * @description 保存司机认证信息      
     */
    @ApiOperation("保存司机认证信息")
    @PostMapping("/saveAuthDetails")
    public R<?> saveAuthDetails(@RequestBody HtDriverFile htDriverFile) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        String id = loginUser.getLoginId();
        int res = 0;
        HtDriverFile driverFile = htDriverFileService.getDriverByUserId(id);
        if (driverFile != null) {
            //更新保存信息
            htDriverFile.setUserId(id);
            User user = systemService.getUser(htDriverFile.getUserId());
            htDriverFile.setUser(user);
            htDriverFile.setIsPassCheck("3");
            htDriverFile.setVersion(1);
            htDriverFile.setId(driverFile.getId());
            htDriverFile.setOffice(driverFile.getOffice());
            htDriverFile.setCompany(driverFile.getCompany());
            htDriverFileService.saveAuthDriver(htDriverFile);
            res = 1;
        } else {
            //首次进行保存时新增
            htDriverFile.setUserId(id);
            User user = systemService.getUser(htDriverFile.getUserId());
            htDriverFile.setUser(user);
            //保存中
            htDriverFile.setIsPassCheck("3");
            htDriverFile.setPhone(user.getMobile());
            htDriverFile.setFactSupplierName(htDriverFile.getName());
            htDriverFile.setCarLicensePic(htDriverFile.getDrivingLicensePic());
            htDriverFile.setVehicleEnergyType(htDriverFile.getVehicleEnergyType());

            Office parent = new Office();
            parent.setId("0");
            Office office = new Office();
            office.setParent(parent);
            office.setType("");
            List<Office> officeList = officeService.findListOnly(office);
            boolean f1 = officeList != null && officeList.size() != 0,
                    f2 = office != null && office.getId() != null;
            if (f1) {
                office = officeList.get(0);
                if (f2) {
                    htDriverFile.setOffice(office);
                    htDriverFile.setCompany(office);
                } else {
                    Office office1 = new Office();
                    office1.setId("1");
                    htDriverFile.setOffice(office1);
                    htDriverFile.setCompany(office1);
                }
            }
            Integer version = htDriverFile.getVersion();
            if (version == null) {
                htDriverFile.setVersion(0);
            }
            if ("请选择".equalsIgnoreCase(htDriverFile.getBaseOpenAccountName())) {
                htDriverFile.setBaseOpenAccountName("");
            }
            htDriverFileService.saveNewDriver(htDriverFile);
            res = 1;
        }
        return R.appOk(res);
    }

    /**
     * 描述:承运商认证
     * @author yangjy
     * @date 2023/6/7 9:41
     * @param htSupplier
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "承运商认证")
    @PostMapping("/saveSupplier")
    public R<?> saveSupplier(@RequestBody HtSupplier htSupplier) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        htSupplier.setUserId(loginUser.getLoginId());
        int res = 0;
        try {
            htSupplier.setPhone(htSupplier.getContactsPhone());
            htSupplier.setUpdateIp("");
            htSupplier.setAuditStatus("0");
            if (StringUtils.isBlank(htSupplier.getId())) {
                HtSupplier htSupplierTmp = htSupplierService.getHtSupplierByUserId(htSupplier.getUserId());
                if (htSupplierTmp != null) {
                    res = 2;
                    return R.appOk(res);
                }
            }
            Office parent = new Office();
            parent.setId("0");
            Office office = new Office();
            office.setParent(parent);
            office.setType("");
            List<Office> officeList = officeService.findListOnly(office);
            if (officeList != null && officeList.size() != 0) {
                office = officeList.get(0);
                if (office != null && office.getId() != null) {
                    htSupplier.setOffice(office);
                    htSupplier.setCompany(office);
                    htSupplier.setCompanyId(office.getId());
                } else {
                    Office office1 = new Office();
                    office1.setId("1");
                    htSupplier.setOffice(office1);
                    htSupplier.setCompany(office1);
                    htSupplier.setCompanyId(office1.getId());
                }
            }
            Integer version = htSupplier.getVersion();
            if (version == null) {
                htSupplier.setVersion(0);
            }
            htSupplierService.save(htSupplier);
            res = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.appOk(res);
    }

    /**
     * 描述: 承运商认证详情
     * @author yangjy
     * @date 2023/6/7 17:45
     * @param htSupplier
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "承运商认证详情")
    @PostMapping(value = "/supplierAuthDetails")
    public R<?> supplierAuthDetails(HtSupplier htSupplier) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        String userId = loginUser.getLoginId();
        if ("3".equals(loginUser.getLoginObject())) {
            htSupplier = htSupplierService.getHtSupplierByUserId(userId);
            if (htSupplier != null) {
                if (StringUtils.isNotEmpty(htSupplier.getId())) {
                    int businessType = htSupplier.getBusinessType();
                    String s = String.valueOf(businessType);
                    String business_type = DictMskUtils.getDictLabel(s, "biz_type", "");
                    htSupplier.setBusinessTypeAlias(business_type);
                }
            }
        }
        return R.appOk(htSupplier);
    }

    /**
     * 描述: 承运商认证保存
     * @author yangjy
     * @date 2023/6/9 14:03
     * @param htSupplier
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "承运商认证保存")
    @PostMapping(value = "/saveAuthSupplier")
    public R<?> saveAuthSupplier(@RequestBody HtSupplier htSupplier) {
        String userId = TokenUtils.getMpLoginUser().getLoginId();
        int res = 0;
        HtSupplier htSupplierFile = htSupplierService.getHtSupplierByUserId(userId);
        if (htSupplierFile != null) {
            //更新保存信息
            htSupplier.setUserId(userId);
            htSupplier.setVersion(1);
            htSupplier.setId(htSupplierFile.getId());
            htSupplier.setPhone(htSupplier.getContactsPhone());
            htSupplier.setUpdateIp("");
            htSupplier.setAuditStatus("3");//  状态: 3 保存
            htSupplierService.save(htSupplier);
            res = 1;
        } else {
            //首次进行保存时新增
            htSupplier.setUserId(userId);
            //保存中
            htSupplier.setPhone(htSupplier.getContactsPhone());
            htSupplier.setUpdateIp("");
            htSupplier.setAuditStatus("3");
            Office parent = new Office();
            parent.setId("0");
            Office office = new Office();
            office.setParent(parent);
            office.setType("");
            List<Office> officeList = officeService.findListOnly(office);
            if (officeList != null && officeList.size() != 0) {
                office = officeList.get(0);
                if (office != null && office.getId() != null) {
                    htSupplier.setOffice(office);
                    htSupplier.setCompany(office);
                    htSupplier.setCompanyId(office.getId());
                } else {
                    Office office1 = new Office();
                    office1.setId("1");
                    htSupplier.setOffice(office1);
                    htSupplier.setCompany(office1);
                    htSupplier.setCompanyId(office1.getId());
                }
            }
            Integer version = htSupplier.getVersion();
            if (version == null) {
                htSupplier.setVersion(0);
            }
            htSupplierService.save(htSupplier);
            res = 1;
        }
        return R.appOk(res);
    }

    @ApiOperation("修改用户头像")
    @PostMapping("/modifyProfile")
    public R<?> modifyProfile(@RequestBody Map<String, String> params) {
        boolean flag = false;
        String photo = params.get("photo");
        LoginUser loginUser = TokenUtils.getMpLoginUser();
        if (StringUtils.isEmpty(photo)) {
            return R.appFail(400101, "头像不能为空");
        }
        if (loginUser != null) {
            User user = systemService.getUser(loginUser.getLoginId());
            user.preUpdate();
            user.setPhoto(photo);
            systemService.updateUserInfo(user);
            flag = true;
        }
        return R.appOk(flag);
    }
}
